import { Auth } from '../entity/user.model';
import * as AuthActions from '../actions/auth.action';
import * as Constant from '../../constant/constant';

/*** 登录权限相关
* */
export function AuthReducer (state: Auth = {
    login: null,
    hasError: true, // 仅登录为false
    device: null, // 设备信息
    errMsg: null,
  }, action: AuthActions.All) {
  switch (action.type) {
    case AuthActions.INIT_DEVICE:
      return Object.assign({}, state, {
        device: action.payload
      });

    // 登录
    case AuthActions.LOGIN_SUCCESS:
      // debugger;
      return {...state,
        login: {
          userId: action.payload.id,
          username: action.payload.get('username'),
        },
        hasError: false,
        errMsg: null,
      };

    case AuthActions.LOGIN_FAILED:
      return {...state,
        login: null,
        hasError: true,
        errMsg: action.payload,
      };

    case AuthActions.LOGOUT:
      return {...state,
        login: null,
        hasError: true,
        errMsg: Constant.LOGIN_AGAIN
      };

    // 注册
    case AuthActions.REGISTER_SUCCESS:
      return {...state,
        login: {
          userId: action.payload.id,
          username: action.payload._serverData.username,
        },
        hasError: true,
        errMsg: Constant.LOGIN_AGAIN
      };

    // 修改密码
    case AuthActions.UPDATE_PASSWORD_SUCCESS:
      return {...state,
        hasError: true,
        errMsg: Constant.LOGIN_AGAIN
      };

    default:
      return state;
  }
}
